from flask_mongoengine.wtf.orm import model_form
from models import User, Game
from wtforms import PasswordField, Field
from wtforms.validators import EqualTo, DataRequired
from wtforms.widgets import TextInput


class TagListField(Field):
    widget = TextInput()

    def _value(self):
        """values on load"""
        if self.data:
            return ', '.join(self.data)
        else:
            return ''

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = [x.strip() for x in valuelist[0].split(',')]
        else:
            self.data = []


# 用mongoengine提供的model_form功能从User类直接创建一个LoginForm类，可以用于验证登陆表单信息
# 不知道为什么model_form的only参数工作始终不正常，只能用exclude
LoginForm = model_form(User, exclude=['active', 'isAdmin', 'timestamp'])

class RegisterForm(LoginForm):
    confirm = PasswordField('重复密码', [DataRequired(), EqualTo('password', message='密码需要两次输入一致')])


GameForm = model_form(Game, exclude=['date_modified', 'date_created'])

class CreateGameForm(GameForm):
    title_translation = TagListField()